<template>
  <div class="login-page">
    <div class="login-wrapper">
      <div class="illustration-section">
        <div class="welcome-message">
          <h2>欢迎使用</h2>
          <h1>爱吃兔 溯源管理系统</h1>
          <p>一个高效、可扩展的后台管理解决方案。</p>
        </div>
      </div>
      <div class="form-section">
        <el-card class="login-card-el" shadow="never">
          <template #header>
            <div class="card-header">
              <span>账户登录</span>
            </div>
          </template>
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" :prefix-icon="User" clearable />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="密码" :prefix-icon="Lock"
                show-password clearable />
            </el-form-item>
            <el-form-item>
              <div class="captcha-row">
                <el-input v-model="captchaInput" maxlength="4" placeholder="验证码" style="width: 140px;" />
                <span class="captcha-img" @click="() => generateCaptcha(true, true)">{{ captcha }}</span>
              </div>
              <div v-if="captchaError" class="captcha-error">{{ captchaError }}</div>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="login-button-el" :loading="loading" @click="handleLogin"
                auto-insert-space>
                {{ loading ? '登录中...' : '登 录' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 导入所需模块和图标
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Right } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { serviceRead } from '@/utils/axionrequest'

// Vue Router实例
const router = useRouter()
// 登录表单的引用
const loginFormRef = ref<FormInstance>()
// 登录按钮的加载状态
const loading = ref(false)

// 响应式的登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// "记住密码"选项的绑定值
const rememberMe = ref(false)

// 验证码相关
const captcha = ref('')
const captchaInput = ref('')
const captchaError = ref('')

function randomChar() {
  const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  return chars.charAt(Math.floor(Math.random() * chars.length))
}
function generateCaptcha(clearInput = false, clearError = false) {
  let str = ''
  for (let i = 0; i < 4; i++) str += randomChar()
  captcha.value = str
  if (clearError) captchaError.value = ''
  if (clearInput) captchaInput.value = ''
}

// 组件挂载时的生命周期钩子
onMounted(() => {
  // 检查localStorage中是否有保存的登录信息
  const saved = localStorage.getItem('rememberLogin')
  if (saved) {
    const { username, password } = JSON.parse(saved)
    loginForm.username = username
    loginForm.password = password
    rememberMe.value = true
  }
  generateCaptcha(true, true)
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录逻辑
const handleLogin = async () => {
  if (!loginFormRef.value) return
  captchaError.value = ''
  if (!captchaInput.value.trim()) {
    captchaError.value = '请输入验证码'
    return
  }
  if (captchaInput.value.trim().toLowerCase() !== captcha.value.toLowerCase()) {
    captchaError.value = '验证码输入不正确，请重新输入'
    return
  }
  try {
    // 触发表单验证
    await loginFormRef.value.validate()
    loading.value = true

    // 如果勾选了"记住密码"，则保存到localStorage
    if (rememberMe.value) {
      localStorage.setItem('rememberLogin', JSON.stringify({
        username: loginForm.username,
        password: loginForm.password
      }))
    } else {
      localStorage.removeItem('rememberLogin')
    }

    // 发起登录请求
    const response = await serviceRead.post('/api/Login/Login', {
      username: loginForm.username,
      password: loginForm.password
    })
    const result = response.data

    // 根据后端返回结果处理
    if (result.code === 200) {
      ElMessage.success('登录成功！')
      // 保存用户信息和Token到localStorage
      localStorage.setItem('userInfo', JSON.stringify(result.data))
      localStorage.setItem('token', result.data.UserId?.toString() || '')
      localStorage.setItem('Token', result.data.Token) // 保存JWT Token
      
      localStorage.setItem('Username',result.data.UserName)//登录人

      // 直接跳转到主页并强制刷新，确保新Token生效
      router.push('/home').then(() => {
        window.location.reload()
      })
    } else {
      ElMessage.error(result.msg || '登录失败')
    }
  } catch (error: any) {
    // 错误处理
    if (error.name === 'ValidationError') {
      ElMessage.warning('请检查输入信息')
    } else if (error.message === '网络错误') {
      ElMessage.error('网络错误，请稍后重试')
    } else {
      ElMessage.error(error.message || '网络错误，请稍后重试')
    }
  } finally {
    // 无论成功或失败，都结束加载状态
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  background-color: #f0f2f5;
  overflow: hidden;
}

.login-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  margin: auto;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.illustration-section {
  width: 60%;
  background: linear-gradient(135deg, #717de9 0%, #7d1ec9 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  position: relative;
  overflow: hidden;
}

.illustration-section::before {
  content: '';
  position: absolute;
  top: -10%;
  left: -10%;
  width: 120%;
  height: 120%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path fill="%23ffffff" opacity="0.1" d="M25 50A25 25 0 1 0-25 50A25 25 0 1 0 25 50z" transform="translate(25 0)"></path><path fill="%23ffffff" opacity="0.1" d="M100 50A50 50 0 1 0 0 50A50 50 0 1 0 100 50z" transform="translate(50 25)"></path><path fill="%23ffffff" opacity="0.1" d="M35 50A35 35 0 1 0-35 50A35 35 0 1 0 35 50z" transform="translate(80 80)"></path></svg>');
  animation: bg-animation 20s infinite linear;
}

@keyframes bg-animation {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.welcome-message {
  text-align: center;
  z-index: 1;
}

.welcome-message h2 {
  font-size: 24px;
  font-weight: 300;
  margin: 0;
}

.welcome-message h1 {
  font-size: 48px;
  font-weight: 700;
  margin: 10px 0;
  letter-spacing: 2px;
}

.welcome-message p {
  font-size: 18px;
  max-width: 400px;
  margin: 10px auto 0;
  line-height: 1.6;
}

.form-section {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
}

.login-card-el {
  width: 400px;
  border: none;
  box-shadow: 0 8px 32px 0 rgba(76, 40, 137, 0.10), 0 1.5px 8px 0 rgba(0,0,0,0.04);
  background: rgba(255,255,255,0.55);
  backdrop-filter: blur(18px);
  -webkit-backdrop-filter: blur(18px);
  border-radius: 28px;
  padding: 48px 36px 36px 36px;
  margin: 32px 0;
}

.card-header {
  text-align: center;
  font-size: 32px;
  font-weight: 800;
  color: #3a2170;
  letter-spacing: 2px;
  margin-bottom: 18px;
}

.login-card-el .el-form-item {
  margin-bottom: 28px;
}

.login-card-el :deep(.el-input__wrapper) {
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(76, 40, 137, 0.04);
  font-size: 18px;
  padding: 8px 18px;
  transition: box-shadow 0.2s, border 0.2s;
}

.login-card-el :deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 4px 16px rgba(124, 40, 221, 0.13);
  border-color: #7c28dd;
}

.login-card-el :deep(.el-input__icon) {
  color: #a0a0b0;
  font-size: 20px;
}

.login-card-el :deep(.el-input__wrapper) {
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(76, 40, 137, 0.04);
  font-size: 18px;
  padding: 8px 18px;
  transition: box-shadow 0.2s, border 0.2s;
}

.login-card-el :deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 4px 16px rgba(124, 40, 221, 0.13);
  border-color: #7c28dd;
}

.login-card-el :deep(.el-input__icon) {
  color: #a0a0b0;
  font-size: 20px;
}

.login-card-el :deep(.el-checkbox) {
  margin-left: 2px;
  font-size: 16px;
  color: #6a4c9d;
}

.login-card-el :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: linear-gradient(90deg, #7c28dd 0%, #4fc3f7 100%);
  border-color: #7c28dd;
}

.login-card-el :deep(.el-checkbox__label) {
  color: #6a4c9d !important;
  font-weight: 500;
  font-size: 16px;
}

.login-button-el {
  width: 100%;
  height: 52px;
  font-size: 20px;
  font-weight: 700;
  border-radius: 18px;
  background: linear-gradient(90deg, #7c28dd 0%, #4fc3f7 100%);
  border: none;
  letter-spacing: 4px;
  box-shadow: 0 4px 16px rgba(124, 40, 221, 0.10);
  transition: background 0.2s, box-shadow 0.2s;
}

.login-button-el:hover,
.login-button-el:focus {
  background: linear-gradient(90deg, #4fc3f7 0%, #7c28dd 100%);
  box-shadow: 0 8px 32px rgba(124, 40, 221, 0.18);
}

.login-card-el .el-form-item:last-child {
  margin-bottom: 0;
}

@media (max-width: 992px) {
  .illustration-section {
    display: none;
  }

  .form-section {
    width: 100%;
  }

  .login-card-el {
    width: 90vw;
    min-width: 0;
    padding: 32px 10vw 24px 10vw;
  }
  .card-header {
    font-size: 24px;
  }
}

.captcha-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.captcha-img {
  display: inline-block;
  min-width: 64px;
  height: 40px;
  line-height: 40px;
  font-size: 22px;
  font-weight: bold;
  color: #7c28dd;
  background: linear-gradient(90deg, #f3e8ff 0%, #e0e7ff 100%);
  border-radius: 10px;
  text-align: center;
  letter-spacing: 4px;
  cursor: pointer;
  user-select: none;
  box-shadow: 0 2px 8px rgba(124, 40, 221, 0.08);
  transition: background 0.2s, color 0.2s;
}
.captcha-img:hover {
  background: linear-gradient(90deg, #e0e7ff 0%, #f3e8ff 100%);
  color: #4fc3f7;
}
.captcha-error {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 4px;
  margin-left: 2px;
}
</style>